layui.define([ 'layer' ], function(exports) {
	var $ = layui.jquery,
		layer = layui.layer;

	var websocket;
	if ('WebSocket' in window) {
		websocket = new WebSocket("ws://" + document.location.host + "/Bank/webSocketServer");
	} else if ('MozWebSocket' in window) {
		websocket = new MozWebSocket("ws://" + document.location.host + "/Bank/webSocketServer");
	} else {
		websocket = new SockJS("http://" + document.location.host + "/Bank/sockjs/webSocketServer");
	}
	websocket.onopen = function(evnt) {};
	websocket.onmessage = function(evnt) {
		if($('#box').hasClass('layui-hide')){
			$('#box').removeClass('layui-hide');
			$('#box').addClass('layui-show');
		}
		var info = JSON.parse(evnt.data);
		$('#cinfobox').prepend('<fieldset class="layui-elem-field layui-field-title">' +
			'<legend>&nbsp;&nbsp;' + info.title + '&nbsp;&nbsp;&nbsp;&nbsp;发布者: ' + info.name + ' &nbsp;' + info.time + '</legend>' +
			'<div class="layui-field-box">' + info.content + '</div></fieldset>');
	};
	websocket.onerror = function(evnt) {};
	websocket.onclose = function(evnt) {};

	//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
	window.onbeforeunload = function() {
		websocket.close();
	}

	exports('send', function(msg) {
		if (websocket.readyState == websocket.OPEN) {
			websocket.send(msg);
		} else {
			layer.msg('连接失败，请尝试刷新', {
				icon : 2,
				time : 1000
			});
		}
	});
});